﻿/* 控件信息
 * 新分页控件。
 * Write By Zeus2
 * 2008-12-17 Last Updated
 * 使用方法 
 * 
 * BindData方法
 * 
    protected void BindData()
    {
        HZ.Data.PageDescribe des = new HZ.Data.PageDescribe(string.Format("SELECT * FROM Account WHERE 1 = 1 {0} ORDER BY AccountID", ViewState["Query"]), 20);
        info.PageSize = 20;
        info.RecordCount = des.TotalCount;
        des.CurrentPage = info.CurrentPage;
        gd1.DataSource = des.GetSpecailPage();
        gd1.DataBind();
    }
 * 
 * 分页事件处理
    protected void Pg(object sender, HZ.Web.PageChaningEventArgs e)
    {
        BindData();
    }
 * 
 * 查询处理
 * protected void Button1_Click(object sender, EventArgs e)
    {
        ViewState["Query"] = GetQueryString();
        info.CurrentPage = 1;
        BindData();
    }
 * 
 */

#region using
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
#endregion
namespace HZ.Web
{
    #region 分页控件
    /// <summary>
    /// Web页面的分页控件，详细信息具体参见WebDemo
    /// </summary>
    /// <example>
    /// 代码示例
    /// <code>
    /// BindData方法 
    ///protected void BindData()
    ///{
    ///HZ.Data.PageDescribe des = new HZ.Data.PageDescribe(string.Format("SELECT * FROM Account WHERE 1 = 1 {0} ORDER BY AccountID", ViewState["Query"]), 20);
    ///info.PageSize = 20;
    ///info.RecordCount = des.TotalCount;
    ///des.CurrentPage = info.CurrentPage;
    ///gd1.DataSource = des.GetSpecailPage();
    ///gd1.DataBind();
    ///} 
    /// //分页事件处理
    ///protected void Pg(object sender, HZ.Web.PageChaningEventArgs e)
    ///{
    ///BindData();
    ///}
    /// // 查询处理
    ///protected void Button1_Click(object sender, EventArgs e)
    ///{
    ///ViewState["Query"] = GetQueryString();
    ///info.CurrentPage = 1;
    ///BindData();
    ///}
    /// </code>
    /// </example>
    [DefaultProperty("Text")]
    [DefaultEvent("PageChanging")]
    [Browsable(true)]
    [ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1>")]
    public class HzPager : WebControl, IPostBackEventHandler, IPostBackDataHandler
    {
        public HzPager()
        {

        }

        #region 属性
        /// <summary>
        /// WebForm页面控件的表现形式,如"上一页 下一页 ［当前 第 0 页　共 0 页　计 0 条］ 转到第 0 页" 
        /// </summary>
        [Category("Appearance")]
        [DefaultValue("")]
        public string Text
        {
            get
            {

                return "上一页 下一页 【当前 第 1 页　共 1 页　计 1 条】转到第 1 页";

            }

        }

        /// <summary>
        /// 信息显示样式
        /// {Current}当前页 {MaxPage}页面总数 {Record}记录总数
        /// 默认【当前 第 {Current} 页　共 {MaxPage} 页　计 {Record} 条】
        /// </summary>
        [Category("Appearance")]
        [Browsable(true)]
        public string Format
        {
            get
            {
                object s = ViewState["Format"];
                if (s == null)
                {
                    return "【当前 第 {Current} 页　共 {MaxPage} 页　计 {Record} 条】";
                }
                else
                {
                    return (string)ViewState["Format"];
                }

            }
            set
            {

                ViewState["Format"] = value;
            }
        }

        /// <summary>
        /// 当前页码
        /// </summary>
        /// <value>
        /// 当前页码
        /// </value>
        [Category("Appearance")]
        public int CurrentPage
        {
            get
            {
                object s = ViewState["CurrentPage"];
                return ((s == null) ? 1 : (int)s);
            }
            set { ViewState["CurrentPage"] = value; }
        }
        /// <summary>
        /// 每一页的记录数量，如果没有设置，默认为10
        /// </summary>
        /// <value>每一页的记录数量，如果没有设置，默认为10</value>
        [DefaultValue(10)]
        [Browsable(true)]
        public int PageSize
        {
            get
            {
                object obj2 = this.ViewState["PageSize"];
                if (obj2 != null)
                {
                    return (int)obj2;
                }
                return 10;


            }
            set
            {
                if (value < 1)
                {
                    throw new ArgumentOutOfRangeException("value");
                }
                if (this.PageSize != value)
                {
                    this.ViewState["PageSize"] = value;
                }
            }
        }

        /// <summary>
        /// 记录总数，为空则设置为1
        /// </summary>
        /// <value>记录总数，为空则设置为1</value>
        [Browsable(false)]
        public int RecordCount
        {
            get
            {
                object s = ViewState["RecordCount"];
                return ((s == null) ? 1 : int.Parse(s.ToString()));
            }
            set { ViewState["RecordCount"] = value; }
        }

        /// <summary>
        /// 获取页总数
        /// </summary>
        /// <value>获取页总数</value>
        public int MaxPage
        {
            get { return (int)((double)RecordCount / PageSize + 0.999999); }
        }

        /// <summary>
        /// 是否显示首页末页
        /// </summary>
        /// <value>是否显示首页末页</value>
        [Category("Appearance")]
        [Browsable(true)]
        [DefaultValue(false)]
        public bool ShowFirstLast
        {
            get
            {
                object o = ViewState["ShowFirstLast"];
                return ((o == null) ? false : (o.ToString().ToLower() == "true"));
            }
            set { ViewState["ShowFirstLast"] = value; }

        }

        #endregion

        #region 展现数据

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
        }
        protected override void RenderContents(HtmlTextWriter output)
        {

            // http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.getpostbackeventreference.aspx

            Page.ClientScript.GetPostBackEventReference(new PostBackOptions(this));

            if (ViewState["RecordCount"] == null)
            {
                output.Write(Text);
                return;
            }

            if (ShowFirstLast)
            {

                if (CurrentPage == 1)
                {
                    output.Write("<font color='#C0C0C0'>首 页</font> ");
                }
                else
                    output.Write(string.Format("<a href=\"javascript:__doPostBack('{0}','{1}')\">首 页</a> ", this.UniqueID, 1));

            }


            if (CurrentPage == 1)
            {
                output.Write("<font color='#C0C0C0'>上一页 </font> ");
            }
            else
                output.Write(string.Format("<a href=\"javascript:__doPostBack('{0}','{1}')\">上一页</a> ", this.UniqueID, CurrentPage - 1));



            if (CurrentPage >= MaxPage)
            {
                output.Write("<font color='#C0C0C0'>下一页</font> ");
            }
            else
                output.Write(string.Format("<a href=\"javascript:__doPostBack('{0}','{1}')\">下一页</a> ", this.UniqueID, CurrentPage + 1));

            if (ShowFirstLast)
            {
                if (CurrentPage >= MaxPage)
                {
                    output.Write("<font color='#C0C0C0'>末 页</font> ");
                }
                else
                    output.Write(string.Format("<a href=\"javascript:__doPostBack('{0}','{1}')\">末 页</a> ", this.UniqueID, MaxPage));
            }

            string tmp = Format.Replace("{Current}", CurrentPage.ToString());
            tmp = tmp.Replace("{MaxPage}", MaxPage.ToString());
            tmp = tmp.Replace("{Record}", RecordCount.ToString());

            output.Write(tmp);
            output.Write(" 转到第");
            output.Write(string.Format("<select id='pager' onchange=\"javascript:__doPostBack('{0}', this.selectedIndex + 1)\">", this.UniqueID));
            for (int i = 1; i <= MaxPage; i++)
            {
                if (CurrentPage == i)
                    output.Write("<option selected>" + i.ToString());
                else
                    output.Write("<option>" + i.ToString());
            }
            output.Write("</select>");

            output.Write("页");
        }
        protected override void OnPreRender(EventArgs e)
        {
            if (Page != null)
            {
            }
            base.OnPreRender(e);
        }
        #endregion

        #region 事件处理


        /// <summary>
        /// 处理页面更改
        /// </summary>
        #region PageChangingEvent

        private static readonly object EventPageChanging = new object();
        public event PageChangingEventHandler PageChanging;


        protected virtual void OnPageChanging(PageChaningEventArgs e)
        {
            if (PageChanging != null)
            {
                CurrentPage = e.NewPage;
                PageChanging(this, e);
            }
        }
        #endregion

        /// <summary>
        /// 处理回传事件
        /// </summary>
        /// <param name="eventArgument"></param>
        #region IPostBackEventHandler Members

        public void RaisePostBackEvent(string eventArgument)
        {
            int newpage = 0;
            if (int.TryParse(eventArgument, out newpage))
            {
                OnPageChanging(new PageChaningEventArgs(newpage));
            }
        }

        #endregion



        #region IPostBackDataHandler Members

        public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
        {
            // throw new NotImplementedException();
            Page.RegisterRequiresPostBack(this);
            return true;
        }

        public void RaisePostDataChangedEvent()
        {
            // throw new NotImplementedException();
        }

        #endregion

        #endregion

        #region 页面验证

        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            if (Page != null)
            {
                Page.VerifyRenderingInServerForm(this);
            }
            base.AddAttributesToRender(writer);
        }

        #endregion

    }

    #endregion

    #region 分页事件
    public delegate void PageChangingEventHandler(object sender, PageChaningEventArgs e);
    public class PageChaningEventArgs : EventArgs
    {
        private int _page;

        public int NewPage
        {
            get { return _page; }
            set { _page = value; }
        }
        public PageChaningEventArgs(int page)
        {
            _page = page;
        }
    }
    #endregion

}
